﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QSettings>
#include <QTextCodec>
#include <QDir>
#include <QFileInfoList>
#include <QFileInfo>
#include <QFileDialog>
#include <QDateTime>
#include <QThread>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    // 初始化界面
    setWindowFlags(Qt::FramelessWindowHint | Qt::WindowMinimizeButtonHint);
    ui->Main_TabB->tabBar()->hide();
    ui->Main_TabC->tabBar()->hide();
    ui->CCD_Tab->tabBar()->hide();
    ui->groupBox_ccd_tab->hide();
    ui->msg_Box->hide();
    ui->Main_BtMotorA->hide();
    ui->Main_BtPLCManage->hide();
    ui->CCD_continueBt->hide();
    //注册数据类型 不然信号槽会数据丢失
    qRegisterMetaType<CameraData>("CameraData");


    // 设置CCD1~CCD4按钮槽函数
    connect(ui->CCD2_OpenFileBt, SIGNAL(clicked()), this, SLOT(on_CCD1_OpenFileBt_clicked()));
    connect(ui->CCD3_OpenFileBt, SIGNAL(clicked()), this, SLOT(on_CCD1_OpenFileBt_clicked()));
    connect(ui->CCD4_OpenFileBt, SIGNAL(clicked()), this, SLOT(on_CCD1_OpenFileBt_clicked()));
    connect(ui->CCD5_OpenFileBt, SIGNAL(clicked()), this, SLOT(on_CCD1_OpenFileBt_clicked()));
    connect(ui->CCD6_OpenFileBt, SIGNAL(clicked()), this, SLOT(on_CCD1_OpenFileBt_clicked()));

    connect(ui->CCD2_UpBt, SIGNAL(clicked()), this, SLOT(on_CCD1_UpBt_clicked()));
    connect(ui->CCD3_UpBt, SIGNAL(clicked()), this, SLOT(on_CCD1_UpBt_clicked()));
    connect(ui->CCD4_UpBt, SIGNAL(clicked()), this, SLOT(on_CCD1_UpBt_clicked()));
    connect(ui->CCD5_UpBt, SIGNAL(clicked()), this, SLOT(on_CCD1_UpBt_clicked()));
    connect(ui->CCD6_UpBt, SIGNAL(clicked()), this, SLOT(on_CCD1_UpBt_clicked()));

    connect(ui->CCD2_DownBt, SIGNAL(clicked()), this, SLOT(on_CCD1_DownBt_clicked()));
    connect(ui->CCD3_DownBt, SIGNAL(clicked()), this, SLOT(on_CCD1_DownBt_clicked()));
    connect(ui->CCD4_DownBt, SIGNAL(clicked()), this, SLOT(on_CCD1_DownBt_clicked()));

    connect(ui->CCD5_DownBt, SIGNAL(clicked()), this, SLOT(on_CCD1_DownBt_clicked()));
    connect(ui->CCD6_DownBt, SIGNAL(clicked()), this, SLOT(on_CCD1_DownBt_clicked()));

    connect(ui->CCD2_StaticBt, SIGNAL(clicked()), this, SLOT(on_CCD1_StaticBt_clicked()));
    connect(ui->CCD3_StaticBt, SIGNAL(clicked()), this, SLOT(on_CCD1_StaticBt_clicked()));
    connect(ui->CCD4_StaticBt, SIGNAL(clicked()), this, SLOT(on_CCD1_StaticBt_clicked()));
    connect(ui->CCD5_StaticBt, SIGNAL(clicked()), this, SLOT(on_CCD1_StaticBt_clicked()));
    connect(ui->CCD6_StaticBt, SIGNAL(clicked()), this, SLOT(on_CCD1_StaticBt_clicked()));


    /* DLG */
    m_dPlc = new PlcDlg(this);
    m_dPlc->hide();

    m_dProduct = new ProductDlg(this);
    m_dProduct->hide();

    /* THREAD */
    m_tCamera1 = new CameraThread();
    m_tCamera2 = new CameraThread();
    m_tCamera3 = new CameraThread();
    m_tCamera4 = new CameraThread();
    m_tCamera5 = new CameraThread();
    m_tCamera6 = new CameraThread();


    m_tAlg1 = new AlgThread();
    m_tAlg2 = new AlgThread();
    m_tAlg3 = new AlgThread();
    m_tAlg4 = new AlgThread();
    m_tAlg5 = new AlgThread();
    m_tAlg6 = new AlgThread();

    m_tSaveImg1 = new SaveImgThread();
    m_tSaveImg2 = new SaveImgThread();
    m_tSaveImg3 = new SaveImgThread();
    m_tSaveImg4 = new SaveImgThread();
    m_tSaveImg5 = new SaveImgThread();
    m_tSaveImg6 = new SaveImgThread();

    // Connect Camera and Alg Thread event
    connect(m_tCamera1->m_worker, &CameraWorker::sigAlgStart, m_tAlg1->m_worker, &AlgWorker::start);
    connect(m_tCamera2->m_worker, &CameraWorker::sigAlgStart, m_tAlg2->m_worker, &AlgWorker::start);
    connect(m_tCamera3->m_worker, &CameraWorker::sigAlgStart, m_tAlg3->m_worker, &AlgWorker::start);
    connect(m_tCamera4->m_worker, &CameraWorker::sigAlgStart, m_tAlg4->m_worker, &AlgWorker::start);
    connect(m_tCamera5->m_worker, &CameraWorker::sigAlgStart, m_tAlg3->m_worker, &AlgWorker::start);
    connect(m_tCamera6->m_worker, &CameraWorker::sigAlgStart, m_tAlg4->m_worker, &AlgWorker::start);



    connect(m_tAlg1->m_worker, &AlgWorker::sigSaveImgStart, m_tSaveImg1->m_worker, &SaveImgWorker::start);
    connect(m_tAlg2->m_worker, &AlgWorker::sigSaveImgStart, m_tSaveImg2->m_worker, &SaveImgWorker::start);
    connect(m_tAlg3->m_worker, &AlgWorker::sigSaveImgStart, m_tSaveImg3->m_worker, &SaveImgWorker::start);
    connect(m_tAlg4->m_worker, &AlgWorker::sigSaveImgStart, m_tSaveImg4->m_worker, &SaveImgWorker::start);
    connect(m_tAlg5->m_worker, &AlgWorker::sigSaveImgStart, m_tSaveImg3->m_worker, &SaveImgWorker::start);
    connect(m_tAlg6->m_worker, &AlgWorker::sigSaveImgStart, m_tSaveImg4->m_worker, &SaveImgWorker::start);

    connect(m_tAlg6->m_worker, &AlgWorker::sigCameraResult, this, &MainWindow::CameraResult);


    // Connect product event
    connect(m_dProduct, &ProductDlg::sigProToMain, this, &MainWindow::SearchProFiles);
    connect(m_dProduct->m_dProCreat, &ProCreateDlg::sigProCreateToMain, this, &MainWindow::SearchProFiles);

    Log("初始化相机");
    // 读取Config 配置文件
    // 初始化 分配参数
    RdConfigIni();


    // 检测相机 个数 是否为配置数 没有报错  不运行启动
    m_control.initSome();
    m_control.UpdateCameraList();
    m_nCurrentCamera = m_control.cameras().size();
    //// 创建文件  赋值存图地址
    CreateCameraSaveFile();
    if (m_nCurrentCamera < m_nCameraNum){
        switch (m_nCurrentCamera) {
        case 0:
            Log("Cannot find Any camera!", 1);
            break;
        default:
            break;
        }

    }
    else{
        // 初始化 相机线程
        m_tCamera1->Initialize();
        m_tCamera2->Initialize();
        m_tCamera3->Initialize();
        m_tCamera4->Initialize();
        m_tCamera5->Initialize();
        m_tCamera6->Initialize();
        ///// 获取检测参数

    }

    SearchProFiles();
    RdProductIni(file_list[m_nProductNum]);



    // 定时器
    // 定时器
    myTimer = new QTimer(this);
    connect(myTimer, &QTimer::timeout, this, &MainWindow::systimer);
    myTimer->start(1000);

    // 保存 检测参数tab 标签
    m_tabA = ui->tab_Alg->widget(0);
    m_tabB = ui->tab_Alg->widget(1);
    m_tabC = ui->tab_Alg->widget(2);
}

MainWindow::~MainWindow()
{
    m_control.deleteAll();

	m_tCamera1->m_worker->m_control->deleteAll();
	m_tCamera2->m_worker->m_control->deleteAll();
	m_tCamera3->m_worker->m_control->deleteAll();
	m_tCamera4->m_worker->m_control->deleteAll();
    m_tCamera5->m_worker->m_control->deleteAll();
    m_tCamera6->m_worker->m_control->deleteAll();
    delete ui;
}
void MainWindow::systimer(){
    if (m_bStart){
        // 计算速率
        m_nTime++;
        if (m_nTime - m_nOldTime == 5){
            m_nOldTime = m_nTime;
            strRev = QString("%1%2").arg(QString::number((((float)m_nCameraResult - (float)m_nRev) / 5) * 60))
                    .arg(" pcs/min");
            m_nRev = m_nCameraResult;
            ui->Main_Blabe_2->setText(strRev);
        }
        // 记录运行时长
        SetRunTime();
    }
    //    // 判断PLC连接
    IsPlcConnect();
    // 连续硬触发
    if(m_nMainCurrent > 0){
        if(m_nContinuous){
            on_CCD_singleBt_clicked();
        }
    }

    //    // 设置时钟
    //    SetClock();

}

void MainWindow::SetRunTime(){
    m_sRunTime = QString("%1h:%2m:%3s").arg(m_nHH).arg(m_nMM, 2, 10, QLatin1Char('0')).arg(m_nSS, 2, 10, QLatin1Char('0'));
    ui->Main_Blabe_7->setText(m_sRunTime);
    m_nSS++;
    if (m_nSS > 59){
        m_nSS = 0;
        m_nMM++;
    }
    if (m_nMM > 59){
        m_nMM = 0;
        m_nHH++;
    }
}

void MainWindow::IsPlcConnect(){
    if(m_dPlc->m_tPlc->m_worker->m_bPlcConnect != bConnect){
        bConnect = m_dPlc->m_tPlc->m_worker->m_bPlcConnect;
        if (bConnect){
            Log("成功：PLC连接成功");
        }
        else{
            Log("错误：PLC连接失败",1);
        }
    }else{
        return;
    }
}



void MainWindow::on_Main_BtMin_clicked()
{
    // min
    setWindowState(Qt::WindowMinimized);
}

void MainWindow::on_Main_BtQuite_clicked()
{
    // quit
    if (!(QMessageBox::question(this, tr("Exit"), QString::fromLocal8Bit("退出？"), tr("Yes"), tr("No"))))
    {
        QApplication* app;
        app->exit(0);
    }
}

void MainWindow::on_Main_BtStartAndStop_clicked()
{
    if (m_nCurrentCamera < 4){
        return;
    }
    OpenHalconWindows();
    // 启动与停止 采集
    if (m_nMainStart){
        m_dPlc->Stop();
        m_bStart = false;
        ui->Main_BtStartAndStop->setStyleSheet("border-image: url(:/main/img/main/Main_BtStart.png)");


        //        切换手动模式
        //        m_tAlg1->m_worker->m_nModel = 1;
        //        m_tAlg2->m_worker->m_nModel = 1;
        //        m_tAlg3->m_worker->m_nModel = 1;
        //        m_tAlg4->m_worker->m_nModel = 1;
    }
    else{
        m_dPlc->Start();
        m_nPlcIndex = 0;
        m_bStart = true;
        //        切换自动模式
        //        m_tAlg1->m_worker->m_nModel = 0;
        //        m_tAlg2->m_worker->m_nModel = 0;
        //        m_tAlg3->m_worker->m_nModel = 0;
        //        m_tAlg4->m_worker->m_nModel = 0;
        ui->Main_BtStartAndStop->setStyleSheet("border-image: url(:/main/img/main/Main_BtStop.png)");
    }
    m_nMainStart = 1 - m_nMainStart;
}


void MainWindow::OpenHalconWindows()
{
    Hlong hWind;
    // Halcon
    if (m_nOpenHalcon){
        return;
    }
    m_nOpenHalcon = 1;
    hWind = ui->Main_CCD1->winId();
    HalconCpp::OpenWindow(0, 0, ui->Main_CCD1->width(), ui->Main_CCD1->height(), hWind, "", "", &m_hvMainHandle1);
    hWind = ui->Main_CCD2->winId();
    HalconCpp::OpenWindow(0, 0, ui->Main_CCD2->width(), ui->Main_CCD2->height(), hWind, "", "", &m_hvMainHandle2);
    hWind = ui->Main_CCD3->winId();
    HalconCpp::OpenWindow(0, 0, ui->Main_CCD3->width(), ui->Main_CCD3->height(), hWind, "", "", &m_hvMainHandle3);
    hWind = ui->Main_CCD4->winId();
    HalconCpp::OpenWindow(0, 0, ui->Main_CCD4->width(), ui->Main_CCD4->height(), hWind, "", "", &m_hvMainHandle4);


    hWind = ui->CCD1_Wind->winId();
    HalconCpp::OpenWindow(0, 0, ui->CCD1_Wind->width(), ui->CCD1_Wind->height(), hWind, "", "", &c1_hvCCDHandle);
    hWind = ui->CCD2_Wind->winId();
    HalconCpp::OpenWindow(0, 0, ui->CCD2_Wind->width(), ui->CCD2_Wind->height(), hWind, "", "", &c2_hvCCDHandle);
    hWind = ui->CCD3_Wind->winId();
    HalconCpp::OpenWindow(0, 0, ui->CCD3_Wind->width(), ui->CCD3_Wind->height(), hWind, "", "", &c3_hvCCDHandle);
    hWind = ui->CCD4_Wind->winId();
    HalconCpp::OpenWindow(0, 0, ui->CCD4_Wind->width(), ui->CCD4_Wind->height(), hWind, "", "", &c4_hvCCDHandle);



    m_tCamera1->m_worker->m_cData.m_nIndex = 1;
    m_tCamera2->m_worker->m_cData.m_nIndex = 2;
    m_tCamera3->m_worker->m_cData.m_nIndex = 3;
    m_tCamera4->m_worker->m_cData.m_nIndex = 4;
    m_tCamera5->m_worker->m_cData.m_nIndex = 3;
    m_tCamera6->m_worker->m_cData.m_nIndex = 4;


    m_tCamera1->m_worker->m_cData.hv_WindowHandle = m_hvMainHandle1;
    m_tCamera2->m_worker->m_cData.hv_WindowHandle = m_hvMainHandle2;
    m_tCamera3->m_worker->m_cData.hv_WindowHandle = m_hvMainHandle3;
    m_tCamera4->m_worker->m_cData.hv_WindowHandle = m_hvMainHandle4;
    m_tCamera5->m_worker->m_cData.hv_WindowHandle = m_hvMainHandle5;
    m_tCamera6->m_worker->m_cData.hv_WindowHandle = m_hvMainHandle6;


    m_tCamera1->start();
    m_tCamera2->start();
    m_tCamera3->start();
    m_tCamera4->start();
    m_tCamera5->start();
    m_tCamera6->start();
}

void MainWindow::RdConfigIni()
{
    Log("读取Config配置文件");
    QString iniFilePath = "Config/config.ini";
    QSettings configIniRead(iniFilePath, QSettings::IniFormat);
    configIniRead.setIniCodec(QTextCodec::codecForName("UTF_8"));

    // 获取相机
    m_nCameraNum = configIniRead.value("CameraNum/Num").toInt();
    for (int i = 0; i < m_nCameraNum; i++){
        QString camera_fileName =
                QString("%1%2%3")
                .arg("Camera_").arg(i + 1).arg("/rStrCameraID");
        m_cameras.push_back(configIniRead.value(camera_fileName).toString());

        camera_fileName = QString("set CCD%1 SN:%2")
                .arg(i + 1).arg(configIniRead.value(camera_fileName).toString());
        Log(camera_fileName.toStdString());
    }

    // 获取产品类型
    m_nProductNum = configIniRead.value("ProductNum/Num").toInt();

    m_tCamera1->m_worker->m_cData.qStrCameraID = m_cameras[0];
    m_tCamera2->m_worker->m_cData.qStrCameraID = m_cameras[1];
    m_tCamera3->m_worker->m_cData.qStrCameraID = m_cameras[2];
    m_tCamera4->m_worker->m_cData.qStrCameraID = m_cameras[3];
    m_tCamera5->m_worker->m_cData.qStrCameraID = m_cameras[4];
    m_tCamera6->m_worker->m_cData.qStrCameraID = m_cameras[5];
}



void MainWindow::changeEvent(QEvent *event)
{
    if (event->type() == QEvent::WindowStateChange)
    {
        if (!isMinimized())
        {
            setAttribute(Qt::WA_Mapped);
        }
    }          QWidget::changeEvent(event);
}

void MainWindow::getCameraAttribute()
{
    if (m_nCurrentCamera < 4){
        return;
    }
    ui->CCD_Edit1->setText(QString::number(m_tCurrentCamera->m_worker->m_control->getExposureTime()));
    ui->CCD_Edit2->setText(QString::number(m_tCurrentCamera->m_worker->m_control->getOffsetX()));
    ui->CCD_Edit3->setText(QString::number(m_tCurrentCamera->m_worker->m_control->getOffsetY()));
    ui->CCD_Edit4->setText(QString::number(m_tCurrentCamera->m_worker->m_control->getCameraHeight()));
    ui->CCD_Edit5->setText(QString::number(m_tCurrentCamera->m_worker->m_control->getCameraWidth()));
    //ui->CCD_Edit8->setText(QString::number(m_tCurrentCamera->m_worker->m_control->getGain()));
}


void MainWindow::ShowImage(HalconCpp::HObject img, HalconCpp::HTuple hvHandle)
{
    HalconCpp::HTuple w, h;
    HalconCpp::GetImageSize(img, &w, &h);
    HalconCpp::SetPart(hvHandle, 0, 0, h, w);
    HalconCpp::DispObj(img, hvHandle);
}


void MainWindow::on_Main_TabA_currentChanged(int index)
{
    m_nMainCurrent = index;
    switch (index) {
    case 0:
        // 跳转主页面
        m_tCamera1->m_worker->m_cData.hv_WindowHandle = m_hvMainHandle1;
        m_tCamera2->m_worker->m_cData.hv_WindowHandle = m_hvMainHandle2;
        m_tCamera3->m_worker->m_cData.hv_WindowHandle = m_hvMainHandle3;
        m_tCamera4->m_worker->m_cData.hv_WindowHandle = m_hvMainHandle4;
        m_tCamera5->m_worker->m_cData.hv_WindowHandle = m_hvMainHandle3;
        m_tCamera6->m_worker->m_cData.hv_WindowHandle = m_hvMainHandle4;



        break;
    case 1:
        // 跳转CCD1
        m_tCurrentCamera = m_tCamera1;
        m_tCamera1->m_worker->m_cData.hv_WindowHandle = c1_hvCCDHandle;

        // 数据展示 ui 界面  变化
        //        ui->CD1_TabA1_1_0->setText("");

        break;
    case 2:
        // 跳转CCD2
        m_tCurrentCamera = m_tCamera2;
        m_tCamera2->m_worker->m_cData.hv_WindowHandle = c2_hvCCDHandle;
        //
        break;
    case 3:
        m_tCurrentCamera = m_tCamera3;
        m_tCamera3->m_worker->m_cData.hv_WindowHandle = c3_hvCCDHandle;
        // 跳转CCD3
        break;
    case 4:
        m_tCurrentCamera = m_tCamera4;
        m_tCamera4->m_worker->m_cData.hv_WindowHandle = c4_hvCCDHandle;
        // 跳转CCD4
        break;
    case 5:
        m_tCurrentCamera = m_tCamera5;
        m_tCamera5->m_worker->m_cData.hv_WindowHandle = c5_hvCCDHandle;
        // 跳转CCD4
        break;
    case 6:
        m_tCurrentCamera = m_tCamera6;
        m_tCamera6->m_worker->m_cData.hv_WindowHandle = c6_hvCCDHandle;
        // 跳转CCD4
        break;

    default:
        break;
    }
    if (index){
        ui->groupBox_ccd_tab->show();
    }
    else{
        ui->groupBox_ccd_tab->hide();
    }


    if (m_nCurrentCamera >= 4){
        getCameraAttribute();
    }


    if (index > 0){
        ui->Main_TabC->setCurrentIndex(1);
        ui->Main_TabB->setCurrentIndex(1);
        ui->msg_Box->show();
        updateAlgInfo();
    }
    else{
        ui->Main_TabC->setCurrentIndex(0);
        ui->Main_TabB->setCurrentIndex(0);
        ui->msg_Box->hide();
    }
}


void MainWindow::OpenFileImg(int index)
{
    QString OpenFile;
    //打开文件夹中的图片文件
    OpenFile = QFileDialog::getOpenFileName(this,
                                            "Please choose an image file",
                                            "",
                                            "Image Files(*.jpg *.png *.bmp *.pgm *.pbm);;All(*.*)");
    if (OpenFile != "")
    {

        OpenHalconWindows();

        // 获取当前文件所有图片名称
        QFileInfo fi;
        QString file_name;
        QString file_path;
        QStringList file_list;
        int file_index = 0;
        fi = QFileInfo(OpenFile);
        file_name = fi.fileName();
        file_path = fi.absolutePath();

        QDir dir(file_path);
        file_list = dir.entryList(QDir::Files | QDir::NoDotAndDotDot);
        file_index = file_list.indexOf(file_name);

        m_vFilePath[index] = file_path;
        m_vFileList[index] = file_list;
        m_vFileIndex[index] = file_index;

        CarouselImage(index);

    }
}

void MainWindow::CarouselImage(int index)
{
    QString OpenFile = QString("%1/%2").arg(m_vFilePath[index]).arg(m_vFileList[index][m_vFileIndex[index]]);

    QTextCodec *code = QTextCodec::codecForName("GB2312");//解决中文路径问题
    std::string name = code->fromUnicode(OpenFile).data();
    isOpenImg = true;

    HalconCpp::ReadImage(&m_hImage, name.c_str());
    QPushButton * pushBt;

    switch (index) {
    case 0:
        pushBt = ui->CCD1_Path;
        m_hvHandle = c1_hvCCDHandle;
        break;
    case 1:
        pushBt = ui->CCD2_Path;
        m_hvHandle = c2_hvCCDHandle;
        break;
    case 2:
        pushBt = ui->CCD3_Path;
        m_hvHandle = c3_hvCCDHandle;
        break;
    case 3:
        pushBt = ui->CCD4_Path;
        m_hvHandle = c4_hvCCDHandle;
        break;
    case 4:
        pushBt = ui->CCD5_Path;
        m_hvHandle = c5_hvCCDHandle;
        break;
    case 5:
        pushBt = ui->CCD6_Path;
        m_hvHandle = c6_hvCCDHandle;
        break;
    default:
        break;
    }
    pushBt->setText(OpenFile);
    ShowImage(m_hImage, m_hvHandle);
}

void MainWindow::on_CCD1_OpenFileBt_clicked()
{
    OpenFileImg(m_nMainCurrent - 1);
}


void MainWindow::on_CCD1_UpBt_clicked()
{
    if(!isOpenImg){
        return;
    }
    ImgUp(m_nMainCurrent - 1);
}

void MainWindow::on_CCD1_DownBt_clicked()
{
    if(!isOpenImg){
        return;
    }
    ImgDown(m_nMainCurrent - 1);
}
void MainWindow::ImgUp(int index)
{
    if (m_vFilePath[index] == NULL){
        return;
    }
    m_vFileIndex[index]--;
    if (m_vFileIndex[index] == -1){
        m_vFileIndex[index] = m_vFileList[index].size() - 1;
    }
    CarouselImage(index);
}

void MainWindow::ImgDown(int index)
{
    if (m_vFilePath[index] == NULL){
        return;
    }
    m_vFileIndex[index]++;
    if (m_vFileIndex[index] == m_vFileList[index].size()){
        m_vFileIndex[index] = 0;
    }
    CarouselImage(index);
}


void MainWindow::SetCombox()
{
    ui->Main_ComboxProduct->clear();
    file_names.clear();
    // comboBox
    for (int i = 0; i < file_list.size(); i++){
        file_names.append(file_list[i].left(file_list[i].indexOf(".ini")));
        ui->Main_ComboxProduct->addItem(file_names[i]);
    }
    m_dProduct->file_names = file_names;
    m_dProduct->updateListInfo();

    if(m_dProduct->m_nIndex){
        ui->Main_ComboxProduct->setCurrentIndex(m_dProduct->m_nIndex);
    }
}



void MainWindow::on_CCD1_StaticBt_clicked()
{
    QTime time;
    if(!isOpenImg){
        return;
    }
    int result = 0;
    QString msg;
    switch (m_nMainCurrent) {
    case 1:
        time.start();
        result = m_tAlg1->m_worker->CCD_Alg(m_hImage);
        ShowImage(m_tAlg1->m_worker->m_defect.m_Image_Show, c1_hvCCDHandle);
        msg = QString("Time:%1s").arg(time.elapsed()/1000.0);
        break;
    case 2:
        time.start();
        result = m_tAlg2->m_worker->CCD_Alg(m_hImage);
        msg = QString("Time:%1s").arg(time.elapsed()/1000.0);
        ShowImage(m_tAlg2->m_worker->m_defect.m_Image_Show,c2_hvCCDHandle);
        break;
    case 3:
        time.start();
        result = m_tAlg3->m_worker->CCD_Alg(m_hImage);
        msg = QString("Time:%1s").arg(time.elapsed()/1000.0);
        ShowImage(m_tAlg3->m_worker->m_defect.m_Image_Show,c3_hvCCDHandle);
        break;
    case 4:
        time.start();
        result = m_tAlg4->m_worker->CCD_Alg(m_hImage);
        msg = QString("Time:%1s").arg(time.elapsed()/1000.0);
        ShowImage(m_tAlg4->m_worker->m_defect.m_Image_Show,c4_hvCCDHandle);
        break;

    case 5:
        time.start();
        result = m_tAlg5->m_worker->CCD_Alg(m_hImage);
        msg = QString("Time:%1s").arg(time.elapsed()/1000.0);
        ShowImage(m_tAlg5->m_worker->m_defect.m_Image_Show,c5_hvCCDHandle);
        break;

    case 6:
        time.start();
        result = m_tAlg6->m_worker->CCD_Alg(m_hImage);
        msg = QString("Time:%1s").arg(time.elapsed()/1000.0);
        ShowImage(m_tAlg6->m_worker->m_defect.m_Image_Show,c6_hvCCDHandle);
        break;
    default:
        break;
    }
    ui->msg_time->setText(msg);
    Msg_Box(result);
}


void MainWindow::Msg_Box(int nMsg)
{
    QString strMsg1;
    QString strMsg2;
    QString NG = "color: rgb(255, 0, 0);";
    QString OK = "color: rgb(85, 255, 255);";
    QString Abnormal = "color: rgb(255, 255, 0);";
    QString msgColor1;
    QString msgColor2;
    switch (nMsg) {
    case -11:
        strMsg1 = QString::fromLocal8Bit("尺寸:异常");
        strMsg2 = QString::fromLocal8Bit("缺陷:异常");
        msgColor1 = Abnormal;
        msgColor2 = Abnormal;
        break;
    case -10:
        strMsg1 = QString::fromLocal8Bit("尺寸:通过");
        strMsg2 = QString::fromLocal8Bit("缺陷:异常");
        msgColor1 = OK;
        msgColor2 = Abnormal;
        break;
    case -9:
        strMsg1 = QString::fromLocal8Bit("尺寸:错误");
        strMsg2 = QString::fromLocal8Bit("缺陷:异常");
        msgColor1 = NG;
        msgColor2 = Abnormal;
        break;
    case -1:
        strMsg1 = QString::fromLocal8Bit("尺寸:异常");
        strMsg2 = QString::fromLocal8Bit("缺陷:通过");
        msgColor1 = Abnormal;
        msgColor2 = OK;
        break;
    case 0:
        strMsg1 = QString::fromLocal8Bit("尺寸:通过");
        strMsg2 = QString::fromLocal8Bit("缺陷:通过");
        msgColor1 = OK;
        msgColor2 = OK;
        break;
    case 1:
        strMsg1 = QString::fromLocal8Bit("尺寸:错误");
        strMsg2 = QString::fromLocal8Bit("缺陷:通过");
        msgColor1 = NG;
        msgColor2 = OK;
        break;
    case 9:
        strMsg1 = QString::fromLocal8Bit("尺寸:异常");
        strMsg2 = QString::fromLocal8Bit("缺陷:错误");
        msgColor1 = Abnormal;
        msgColor2 = NG;
        break;
    case 10:
        strMsg1 = QString::fromLocal8Bit("尺寸:通过");
        strMsg2 = QString::fromLocal8Bit("缺陷:错误");
        msgColor1 = OK;
        msgColor2 = NG;
        break;
    case 11:
        strMsg1 = QString::fromLocal8Bit("尺寸:错误");
        strMsg2 = QString::fromLocal8Bit("缺陷:错误");
        msgColor1 = NG;
        msgColor2 = NG;
        break;
    default:
        break;
    }
    ui->msg_size->setStyleSheet(msgColor1);
    ui->msg_defect->setStyleSheet(msgColor2);

    ui->msg_size->setText(strMsg1);
    ui->msg_defect->setText(strMsg2);
}



void MainWindow::on_CCD_changeBT_clicked()
{
    // 修改相机 基本属性
    setCameraAttribute();
}
void MainWindow::setCameraAttribute()
{
    m_tCurrentCamera->m_worker->m_control->setExposureTime(ui->CCD_Edit1->text().toInt());
//    m_tCurrentCamera->m_worker->m_control->setOffsetX(ui->CCD_Edit2->text().toInt());
//    m_tCurrentCamera->m_worker->m_control->setOffsetY(ui->CCD_Edit3->text().toInt());
//    m_tCurrentCamera->m_worker->m_control->setCameraHeight(ui->CCD_Edit4->text().toInt());
//    m_tCurrentCamera->m_worker->m_control->setCameraWidth(ui->CCD_Edit5->text().toInt());
//    m_tCurrentCamera->m_worker->m_control->setCameraGain(ui->CCD_Edit8->text().toInt());
    getCameraAttribute();

    QMessageBox::information(this, QString::fromLocal8Bit("成功"), QString::fromLocal8Bit("修改成功！"));
}

QString MainWindow::GetTime(){
    QDateTime current_date_time = QDateTime::currentDateTime();
    QString current_date = current_date_time.toString("yyyy-MM-dd hh:mm:ss");
    return current_date;
}
void MainWindow::Log(std::string strMsg, int type)
{
    QListWidgetItem *item = new QListWidgetItem();
    QString Msg = QString::fromLocal8Bit(strMsg.c_str());
    Msg = QString("%1:%2").arg(GetTime()).arg(Msg);
    QFont font;
    font.setBold(true);
    font.setFamily("微软雅黑");
    font.setPointSize(14);
    item->setText(Msg);
    item->setFont(font);

    switch (type) {
    case 0:
        item->setTextColor(QColor(85, 255, 255));
        break;
    case 1:
        item->setTextColor(QColor(255, 0, 127));
        break;
    default:
        break;
    }
    ui->Main_msgList->insertItem(0, item);
}

void MainWindow::on_Main_BtPic_clicked()
{
    // 切换 原图 瑕疵图
    m_swSaveImg.nSwPic = 1 - m_swSaveImg.nSwPic;
    if (m_swSaveImg.nSwPic){
        ui->Main_BtPic->setText(QString::fromLocal8Bit("瑕疵图"));
    }
    else{
        ui->Main_BtPic->setText(QString::fromLocal8Bit("原图"));
    }
}

void MainWindow::on_Main_BtNGorAND_clicked()
{
    // 切换 NG OK
    m_swSaveImg.nSwNg = 1 - m_swSaveImg.nSwNg;
    if (m_swSaveImg.nSwNg){
        ui->Main_BtNGorAND->setText("OkAndNg");
    }
    else{
        ui->Main_BtNGorAND->setText("NG");
    }
}

void MainWindow::on_Main_SBtCCD1_clicked()
{
    m_swSaveImg.nCCD1 = 1 - m_swSaveImg.nCCD1;
    QPushButton* pSwBt = ui->Main_SBtCCD1;
    ShowSwitchBt(pSwBt, m_swSaveImg.nCCD1, 0);
}

void MainWindow::on_Main_SBtCCD2_clicked()
{
    m_swSaveImg.nCCD2 = 1 - m_swSaveImg.nCCD2;
    QPushButton* pSwBt = ui->Main_SBtCCD2;
    ShowSwitchBt(pSwBt, m_swSaveImg.nCCD2, 0);
}

void MainWindow::on_Main_SBtCCD3_clicked()
{
    m_swSaveImg.nCCD3 = 1 - m_swSaveImg.nCCD3;
    QPushButton* pSwBt = ui->Main_SBtCCD3;
    ShowSwitchBt(pSwBt, m_swSaveImg.nCCD3, 0);
}

void MainWindow::on_Main_SBtCCD4_clicked()
{
    m_swSaveImg.nCCD4 = 1 - m_swSaveImg.nCCD4;
    QPushButton* pSwBt = ui->Main_SBtCCD4;
    ShowSwitchBt(pSwBt, m_swSaveImg.nCCD4, 0);
}

void MainWindow::on_Main_SBtCCD5_clicked()
{
    m_swSaveImg.nCCD5 = 1 - m_swSaveImg.nCCD5;
    QPushButton* pSwBt = ui->Main_SBtCCD5;
    ShowSwitchBt(pSwBt, m_swSaveImg.nCCD5, 0);
}

void MainWindow::on_Main_SBtCCD6_clicked()
{
    m_swSaveImg.nCCD6 = 1 - m_swSaveImg.nCCD6;
    QPushButton* pSwBt = ui->Main_SBtCCD6;
    ShowSwitchBt(pSwBt, m_swSaveImg.nCCD6, 0);
}

void MainWindow::on_Main_CBtCCD1_clicked()
{
    m_swCheck.nCCD1 = 1 - m_swCheck.nCCD1;
    QPushButton* pSwBt = ui->Main_CBtCCD1;
    ShowSwitchBt(pSwBt, m_swCheck.nCCD1, 1);
}
void MainWindow::on_Main_CBtCCD2_clicked()
{
    m_swCheck.nCCD2 = 1 - m_swCheck.nCCD2;
    QPushButton* pSwBt = ui->Main_CBtCCD2;
    ShowSwitchBt(pSwBt, m_swCheck.nCCD2, 1);
}
void MainWindow::on_Main_CBtCCD3_clicked()
{
    m_swCheck.nCCD3 = 1 - m_swCheck.nCCD3;
    QPushButton* pSwBt = ui->Main_CBtCCD3;
    ShowSwitchBt(pSwBt, m_swCheck.nCCD3, 1);
}
void MainWindow::on_Main_CBtCCD4_clicked()
{
    m_swCheck.nCCD4 = 1 - m_swCheck.nCCD4;
    QPushButton* pSwBt = ui->Main_CBtCCD4;
    ShowSwitchBt(pSwBt, m_swCheck.nCCD4, 1);
}
void MainWindow::on_Main_CBtCCD5_clicked()
{
    m_swCheck.nCCD5 = 1 - m_swCheck.nCCD5;
    QPushButton* pSwBt = ui->Main_CBtCCD5;
    ShowSwitchBt(pSwBt, m_swCheck.nCCD5, 1);
}

void MainWindow::on_Main_CBtCCD6_clicked()
{
    m_swCheck.nCCD6 = 1 - m_swCheck.nCCD6;
    QPushButton* pSwBt = ui->Main_CBtCCD6;
    ShowSwitchBt(pSwBt, m_swCheck.nCCD6, 1);
}

void MainWindow::ShowSwitchBt(QPushButton *pSwBt, int nState, int nIndex)
{
    // 切换  存图   测量 状态
    m_tAlg1->m_worker->m_swSaveImg = m_swSaveImg;
    m_tAlg2->m_worker->m_swSaveImg = m_swSaveImg;
    m_tAlg3->m_worker->m_swSaveImg = m_swSaveImg;
    m_tAlg4->m_worker->m_swSaveImg = m_swSaveImg;
    m_tAlg5->m_worker->m_swSaveImg = m_swSaveImg;
    m_tAlg6->m_worker->m_swSaveImg = m_swSaveImg;
    QString strSheetA = "border-image: url(:/main/img/main/Main_SBtCCD.png);";
    QString strSheetB = "border-image: url(:/main/img/main/Main_SBtCCD2.png);";
    if (nState){
        pSwBt->setStyleSheet(strSheetA);
    }
    else{
        pSwBt->setStyleSheet(strSheetB);
    }
}

void MainWindow::on_Main_BtPLCManage_clicked()
{
    // 打开PLC 设置
    m_dPlc->show();
}

void MainWindow::on_CCD_ComboxInfo_activated(int index)
{
    switch (index) {
    case 0:
        ui->CCD_Tab->setCurrentIndex(index);
        break;
    case 1:
        ui->CCD_Tab->setCurrentIndex(index);
        break;
    default:
        break;
    }
}
void MainWindow::CreateCameraSaveFile()
{
    QDir dir;
    QString imgPath = QDir::currentPath() + "/Pic";
    QString CalPath = QDir::currentPath() + "/Cal";
    bool img = dir.exists(imgPath);
    bool cal = dir.exists(CalPath);
    if (!img)
    {
        dir.mkdir(imgPath);

        dir.mkdir(imgPath + "/ccd1");
        dir.mkdir(imgPath + "/ccd1/OK");
        dir.mkdir(imgPath + "/ccd1/NG");
        dir.mkdir(imgPath + "/ccd1/Abnormal");

        dir.mkdir(imgPath + "/ccd2");
        dir.mkdir(imgPath + "/ccd2/OK");
        dir.mkdir(imgPath + "/ccd2/NG");
        dir.mkdir(imgPath + "/ccd2/Abnormal");

        dir.mkdir(imgPath + "/ccd3");
        dir.mkdir(imgPath + "/ccd3/OK");
        dir.mkdir(imgPath + "/ccd3/NG");
        dir.mkdir(imgPath + "/ccd3/Abnormal");

        dir.mkdir(imgPath + "/ccd4");
        dir.mkdir(imgPath + "/ccd4/OK");
        dir.mkdir(imgPath + "/ccd4/NG");
        dir.mkdir(imgPath + "/ccd4/Abnormal");

        dir.mkdir(imgPath + "/ccd5");
        dir.mkdir(imgPath + "/ccd5/OK");
        dir.mkdir(imgPath + "/ccd5/NG");
        dir.mkdir(imgPath + "/ccd5/Abnormal");


        dir.mkdir(imgPath + "/ccd6");
        dir.mkdir(imgPath + "/ccd6/OK");
        dir.mkdir(imgPath + "/ccd6/NG");
        dir.mkdir(imgPath + "/ccd6/Abnormal");

    }
    if (!cal)
    {
        dir.mkdir(CalPath);
        dir.mkdir(CalPath + "/Cal_Cricle");

        dir.mkdir(CalPath + "/Cal_Cricle/Pic");
        dir.mkdir(CalPath + "/Cal_Length");
        dir.mkdir(CalPath + "/Cal_Length/Pic");
        QFile filename1(CalPath + "/Cal_Cricle/Cricle.txt");
        filename1.open(QIODevice::WriteOnly);
        filename1.close();
        QFile filename2(CalPath + "/Cal_Length/Length.txt");
        filename2.open(QIODevice::WriteOnly);
        filename2.close();
    }
}

void MainWindow::CameraResult(int m_nResult)
{
    // 发送给PLC 结果
    AlgRule(m_nResult);
    // 界面显示
    ShowUI();
}
void MainWindow::ShowUI(){
    float goodRatio1 = 0;
    float goodRatio2 = 0;
    float goodRatio3 = 0;
    float goodRatio4 = 0;
    if (m_nGod1)
    {
        goodRatio1 = float(m_nGod1) / float(m_nCameraResult);
    }
    if (m_nGod2)
    {
        goodRatio2 = float(m_nGod2) / float(m_nCameraResult);
    }
    if (m_nGod3)
    {
        goodRatio3 = float(m_nGod3) / float(m_nCameraResult);
    }
    if (m_nGod4)
    {
        goodRatio4 = float(m_nGod4) / float(m_nCameraResult);
    }

    QString strLabel_13 = QString("%1%2").arg(QString::number(goodRatio1 * 100, 'f', 2)).arg("%");
    QString strLabel_14 = QString("%1%2").arg(QString::number(goodRatio2 * 100, 'f', 2)).arg("%");
    QString strLabel_15 = QString("%1%2").arg(QString::number(goodRatio3 * 100, 'f', 2)).arg("%");
    QString strLabel_16 = QString("%1%2").arg(QString::number(goodRatio4 * 100, 'f', 2)).arg("%");


    ui->Main_Alabe_7->setText(QString::number(m_nGod1));
    ui->Main_Alabe_8->setText(QString::number(m_nGod2));
    ui->Main_Alabe_9->setText(QString::number(m_nGod3));
    ui->Main_Alabe_10->setText(QString::number(m_nGod4));

    if(m_swCheck.nCCD1){
        ui->Main_Alabe_1->setText(QString::number(m_nCameraResult));
        ui->Main_Alabe_13->setText(strLabel_13);
    }
    if(m_swCheck.nCCD2){
        ui->Main_Alabe_2->setText(QString::number(m_nCameraResult));
        ui->Main_Alabe_14->setText(strLabel_14);
    }
    if(m_swCheck.nCCD3){
        ui->Main_Alabe_3->setText(QString::number(m_nCameraResult));
        ui->Main_Alabe_15->setText(strLabel_15);
    }
    if(m_swCheck.nCCD4){
        ui->Main_Alabe_4->setText(QString::number(m_nCameraResult));
        ui->Main_Alabe_16->setText(strLabel_16);
    }





    ui->Main_Alabe_19->setText(QString::number(m_nBad1));
    ui->Main_Alabe_20->setText(QString::number(m_nBad2));
    ui->Main_Alabe_21->setText(QString::number(m_nBad3));
    ui->Main_Alabe_22->setText(QString::number(m_nBad4));

    ui->Main_Blabe_1->setText(QString::number(m_nCameraResult));
    ui->Main_Blabe_3->setText(QString::number(m_nOK));

    float goodRatio = 0;
    float badRatio = 0;
    if (m_nCameraResult)
    {
        goodRatio = float(m_nOK) / float(m_nCameraResult);
        badRatio = float(m_nCameraResult - m_nOK) / float(m_nCameraResult);
    }

    QString strgood = QString("%1%2").arg(QString::number(goodRatio * 100, 'f', 2)).arg("%");
    QString strbad = QString("%1%2").arg(QString::number(badRatio * 100, 'f', 2)).arg("%");
    ui->Main_Blabe_4->setText(strgood);
    ui->Main_Blabe_5->setText(QString::number(m_nCameraResult - m_nOK));
    ui->Main_Blabe_6->setText(strbad);

    ui->Main_Blabe_8->setText(QString::number(m_nNG1));
    ui->Main_Blabe_9->setText(QString::number(m_nNG2));
    ui->Main_Blabe_10->setText(QString::number(m_nNG3));
    ui->Main_Blabe_11->setText(QString::number(m_nOK));


}
void MainWindow::AlgRule(int nIndex){
    // OK   105
    // NG1  100   尺寸  + 缺陷
    // NG2  101   只有缺陷
    // NG3  102   异常

    int nNorOK = 0;
    int nNGorOK1 = m_tAlg1->m_worker->m_nNGorOK[nIndex];
    int nNGorOK2 = m_tAlg2->m_worker->m_nNGorOK[nIndex];
    int nNGorOK3 = m_tAlg3->m_worker->m_nNGorOK[nIndex];
    int nNGorOK4 = m_tAlg4->m_worker->m_nNGorOK[nIndex];
    QList<int> m_listA = QList<int>() << 1 << 11;
    QList<int> m_listC = QList<int>() << -1 << 9 << -10 << -9 << -11;
    QList<int> m_lists = QList<int>() << nNGorOK1 <<nNGorOK2 << nNGorOK3 << nNGorOK4;
    m_nCameraResult++;
    if(m_swCheck.nCCD1){
        if (!nNGorOK1){
            m_nGod1++;
        }else{
            m_nBad1++;
        }
    }else{
        nNGorOK1 = 0;
    }

    if(m_swCheck.nCCD2){
        if (!nNGorOK2){
            m_nGod2++;
        }else{
            m_nBad2++;
        }
    }else{
        nNGorOK2 = 0;
    }

    if(m_swCheck.nCCD3){
        if (!nNGorOK3){
            m_nGod3++;
        }else{
            m_nBad3++;
        }
    }else{
        nNGorOK3 = 0;
    }

    if(m_swCheck.nCCD4){
        if (!nNGorOK4){
            m_nGod4++;
        }else{
            m_nBad4++;
        }
    }else{
        nNGorOK4 = 0;
    }


    bool bState;
    if (nNGorOK3 == 0 && nNGorOK4 == 0 && nNGorOK1 == 0 && nNGorOK2 == 0){
        nNorOK = 105;
        m_nOK++;
        SendPlcResult(nNorOK);
        return;
    }
    else{
        for(int i = 0;i < 4;i++){
            bState = m_listC.contains(m_lists[i]);
            if(bState){
                nNorOK = 102;
                m_nNG3++;
                SendPlcResult(nNorOK);
                return;
            }
        }

        for(int i = 0;i < 4;i++){
            bState = m_listA.contains(m_lists[i]);
            if(bState){
                nNorOK = 100;
                m_nNG1++;
                SendPlcResult(nNorOK);
                return;
            }
        }
        nNorOK = 101;
        m_nNG2++;
        SendPlcResult(nNorOK);
        return;
    }
}

void MainWindow::SendPlcResult(int result)
{
    m_dPlc->m_tPlc->m_worker->writePlcInfo(RESULT_NUMBER,m_nPlcIndex);
    m_dPlc->m_tPlc->m_worker->writePlcInfo(CAMERA_RESULT,result);
    m_nPlcIndex += 2;
    if (m_nPlcIndex == 200){
        m_nPlcIndex = 0;
    }
}

void MainWindow::RdProductIni(QString iniFilePath)
{
    QString Path = "Config/Product/" + iniFilePath;
    QSettings iniRead(Path, QSettings::IniFormat);
    iniRead.setIniCodec(QTextCodec::codecForName("UTF_8"));


    // 获取 设置产品 规格类型
    int nType = iniRead.value("Type/type").toInt();
    QString strSize = iniRead.value("Type/size").toString();


    ui->Main_ComboxType->setCurrentIndex(nType);
    ui->Main_EditSize->setText(strSize);

    // 获取检测参数

    float* fRect1 = &m_tAlg1->m_worker->m_measureRect.m_part.para1;
    float* fRect2 = &m_tAlg2->m_worker->m_measureRect.m_part.para1;
    float* fRect3 = &m_tAlg3->m_worker->m_measureRect.m_part.para1;
    float* fRect4 = &m_tAlg4->m_worker->m_measureRect.m_part.para1;

    float* fTrapezoid1 = &m_tAlg1->m_worker->m_measureTrapezoid.m_part.para1;
    float* fTrapezoid2 = &m_tAlg2->m_worker->m_measureTrapezoid.m_part.para1;
    float* fTrapezoid3 = &m_tAlg3->m_worker->m_measureTrapezoid.m_part.para1;
    float* fTrapezoid4 = &m_tAlg4->m_worker->m_measureTrapezoid.m_part.para1;


    int* nIndex1 = &m_tAlg1->m_worker->m_defect.m_part.parame0;
    int* nIndex2 = &m_tAlg2->m_worker->m_defect.m_part.parame0;
    int* nIndex3 = &m_tAlg3->m_worker->m_defect.m_part.parame0;
    int* nIndex4 = &m_tAlg4->m_worker->m_defect.m_part.parame0;


    QList<float*> m_lRect = QList<float*>() << fRect1 << fRect2 << fRect3 << fRect4;
    QList<float*> m_lTrapezoid = QList<float*>() << fTrapezoid1 << fTrapezoid2 << fTrapezoid3 << fTrapezoid4;
    QList<int*> m_lDefect = QList<int*>() << nIndex1 << nIndex2 << nIndex3 << nIndex4;

    for(int i  = 0;i < 4; i++){
        for(int j = 0; j < 19; j++){
            *m_lRect[i] = iniRead.value(QString("Rect_%1/parame%2").arg(i+1).arg(j)).toFloat();
            m_lRect[i]++;

            *m_lTrapezoid[i] = iniRead.value(QString("Trapezoid_%1/parame%2").arg(i+1).arg(j)).toFloat();
            m_lTrapezoid[i]++;
        }

        for(int j = 0; j < 22; j++){
            *m_lDefect[i] = iniRead.value(QString("Defect_%1/parame%2").arg(i+1).arg(j)).toInt();
            m_lDefect[i]++;
        }
    }

    // 读取检测设置
    int* swAlg = &m_tAlg1->m_worker->m_swAlg.m_ccd1.nCCD;

    QString sInfo;
    for (int a = 0; a < 20; a++)
    {
        sInfo = QString("AlgSwitch/parame%1").arg(a);
        *swAlg = iniRead.value(sInfo).toInt();
        swAlg++;
    }
    m_tAlg2->m_worker->m_swAlg = m_tAlg1->m_worker->m_swAlg;
    m_tAlg3->m_worker->m_swAlg = m_tAlg1->m_worker->m_swAlg;
    m_tAlg4->m_worker->m_swAlg = m_tAlg1->m_worker->m_swAlg;

    setAlgOptions(m_tAlg1,m_tAlg1->m_worker->m_swAlg.m_ccd1);
    setAlgOptions(m_tAlg2,m_tAlg1->m_worker->m_swAlg.m_ccd2);
    setAlgOptions(m_tAlg3,m_tAlg1->m_worker->m_swAlg.m_ccd3);
    setAlgOptions(m_tAlg4,m_tAlg1->m_worker->m_swAlg.m_ccd4);

    updateAlgInfo();
}

void MainWindow::RdModeId()
{
    QString path = QDir::currentPath() + "/Template/1.shm";
    HTuple ModelID;
    HalconCpp::ReadShapeModel(path.toStdString().c_str(), &ModelID);
}



void MainWindow::SearchProFiles()
{

    // 获取当前文件所有Ini名称
    QString path = QDir::currentPath() + "/Config/Product";
    QDir dir(path);
    file_list = dir.entryList(QDir::Files | QDir::NoDotAndDotDot);

    if (file_list.size() == 1){
        m_dProduct->ui->deleteBt->setEnabled(false);
    }
    else{
        m_dProduct->ui->deleteBt->setEnabled(true);
    }
    SetCombox();
}

//删除文件夹
bool MainWindow::deleteDir(const QString &path)
{

    if (path.isEmpty()){
        return false;
    }
    QDir dir(path);
    if (!dir.exists()){
        return true;
    }
    dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot); //设置过滤
    QFileInfoList fileList = dir.entryInfoList(); // 获取所有的文件信息
    foreach(QFileInfo file, fileList){ //遍历文件信息
        if (file.isFile()){ // 是文件，删除
            file.dir().remove(file.fileName());
        }
        else{ // 递归删除
            deleteDir(file.absoluteFilePath());
        }
    }
    return true;
}

void MainWindow::on_Main_BtReset_clicked()
{
    // 数据重置
    ClearCameraData();
}

void MainWindow::on_Main_BtProductManage_clicked()
{
    // 生产管理
    m_dProduct->show();
}

void MainWindow::ClearCameraData(){
    m_nDelet = 0;  // 删除图片数据
    m_nNG1 = 0;
    m_nNG2 = 0;
    m_nNG3 = 0;
    m_nOK = 0;

    m_nRev = 0;  // 速率
    m_nTime = 0;
    m_nOldTime = 0;

    // 速率
    strRev = "0";

    // 运行时间

    m_nSS = 0;
    m_nMM = 0;
    m_nHH = 0;
    m_nDay = 0;

    m_nCameraResult = 0; // 运算结果总量
    m_nGod1 = 0;
    m_nGod2 = 0;
    m_nGod3 = 0;
    m_nGod4 = 0;

    m_nBad1 = 0;
    m_nBad2 = 0;
    m_nBad3 = 0;
    m_nBad4 = 0;

    m_sRunTime = "";

    ShowUI();
    SetRunTime();
}

void MainWindow::on_Main_BtLight_clicked()
{
    // 启动照明
    m_dPlc->on_inBT_25_clicked();
}

void MainWindow::on_Main_BtDiscA_clicked()
{
    // 启动震动盘
    m_dPlc->on_inBT_7_clicked();
}

void MainWindow::on_Main_BtMotorA_clicked()
{
    // 启动上料电机
}

void MainWindow::on_Main_BtDiscB_clicked()
{
    // 启动玻璃盘
    m_nMoto1 = 1-m_nMoto1;
    m_dPlc->m_tPlc->m_worker->writePlcInfo(MOTOR1,m_nMoto1);
}

void MainWindow::on_Main_BtLogin_clicked()
{
    // 登录
    ui->Main_BtPLCManage->show();
}

void MainWindow::on_Main_BtLogout_clicked()
{
    // 锁定
    ui->Main_BtPLCManage->hide();
}

void MainWindow::on_CCD_singleBt_clicked()
{
    // 单张硬触发
    switch(m_nMainCurrent){
    case 1:
        m_dPlc->on_inBT_10_clicked();
        break;
    case 2:
        m_dPlc->on_inBT_11_clicked();
        break;
    case 3:
        m_dPlc->on_inBT_12_clicked();
        break;
    case 4:
        m_dPlc->on_inBT_13_clicked();
        break;
    default:
        break;
    }
}

void MainWindow::on_CCD_plateBt_clicked()
{
    // 启动玻璃盘
    on_Main_BtDiscB_clicked();
}

void MainWindow::on_CCD_multiBt_clicked()
{
    // 连续硬触发
    m_nContinuous = 1 - m_nContinuous;

}

void MainWindow::on_pushButton_9_clicked()
{
    // 导入CAD
}

void MainWindow::on_Main_ComboxProduct_currentIndexChanged(int index)
{
    // 选择产品
    if (index < 0){
        return;
    }
    m_nProductNum = index;
    RdProductIni(file_list[index]);
}

void MainWindow::on_changeBt_clicked()
{
    if(!m_nMainCurrent){
        return;
    }
    QString iniFilePath = "Config/Product/" + file_list[m_nProductNum];
    QSettings configIniWrite(iniFilePath, QSettings::IniFormat);
    configIniWrite.setIniCodec(QTextCodec::codecForName("UTF_8"));
    QString sInfo;

    // 清除 参数UI
    float* fRect;
    float* fTrapezoid;
    int* nDefect;

    AlgThread* m_tAlg;
    switch (m_nMainCurrent)
    {
    case 1:
        m_tAlg = m_tAlg1;
        break;
    case 2:
        m_tAlg = m_tAlg2;
        break;
    case 3:
        m_tAlg = m_tAlg3;
        break;
    case 4:
        m_tAlg = m_tAlg4;
        break;
    default:
        return;
        break;
    }
    nDefect = &m_tAlg->m_worker->m_defect.m_part.parame0;
    fRect = &m_tAlg->m_worker->m_measureRect.m_part.para1;
    fTrapezoid = &m_tAlg->m_worker->m_measureTrapezoid.m_part.para1;

    QLineEdit* lE;
    for (int i = 0; i < 22; i++){
        lE = this->findChild<QLineEdit*>("ccd_defect_" + QString::number(i + 1));
        *nDefect = lE->text().toInt();
        sInfo = QString("Defect_%1/parame%2").arg(m_nMainCurrent).arg(i);
        configIniWrite.setValue(sInfo, lE->text());
        nDefect++;
    }

    for (int i = 0; i < 19; i++)
    {
        lE = this->findChild<QLineEdit*>("ccd_trapezoid_" + QString::number(i + 1));
        *fTrapezoid = lE->text().toFloat();
        sInfo = QString("Trapezoid_%1/parame%2").arg(m_nMainCurrent).arg(i);
        configIniWrite.setValue(sInfo, lE->text());
        fTrapezoid++;
    }
    for (int i = 0; i < 19; i++)
    {
        lE = this->findChild<QLineEdit*>("ccd_rect_" + QString::number(i + 1));
        *fRect = lE->text().toFloat();
        sInfo = QString("Rect_%1/parame%2").arg(m_nMainCurrent).arg(i);
        configIniWrite.setValue(sInfo, lE->text());
        fRect++;
    }
    QMessageBox::information(this, tr("Success"), QString::fromLocal8Bit("写入成功！"));
}

void MainWindow::on_ClearBt_clicked()
{
    //    清除图片
    if (QMessageBox::information(this, QString::fromLocal8Bit("提示"), QString::fromLocal8Bit("以下操作会清除所有图片！"), tr("Yes"), tr("No")))
    {
        return;
    }
    QString imgPath = QDir::currentPath() + "/Pic";
    deleteDir(imgPath);
    QMessageBox::information(this, QString::fromLocal8Bit("成功"), QString::fromLocal8Bit("所有图片已经清除完成！"));
}
void MainWindow::updateAlgInfo()
{
    // 更新检测值
    if(!m_nMainCurrent){
        return;
    }
    // 清除 参数UI
    ui->tab_Alg->clear();
    SW_AlgPart m_ccd;
    float* fRect;
    float* fTrapezoid;
    int* nDefect;
	AlgThread* m_tAlg;
    switch (m_nMainCurrent)
    {
    case 1:
        m_ccd = m_tAlg1->m_worker->m_swAlg.m_ccd1;
        m_tAlg = m_tAlg1;
        break;
    case 2:
        m_ccd = m_tAlg2->m_worker->m_swAlg.m_ccd2;
        m_tAlg = m_tAlg2;
        break;
    case 3:
        m_ccd = m_tAlg3->m_worker->m_swAlg.m_ccd3;
        m_tAlg = m_tAlg3;
        break;
    case 4:
        m_ccd = m_tAlg4->m_worker->m_swAlg.m_ccd4;
        m_tAlg = m_tAlg4;
        break;
    default:
        return;
        break;
    }

    fRect = &m_tAlg->m_worker->m_measureRect.m_part.para1;
    fTrapezoid = &m_tAlg->m_worker->m_measureTrapezoid.m_part.para1;
    nDefect = &m_tAlg->m_worker->m_defect.m_part.parame0;



    QLineEdit* lE;
    for (int i = 0; i < 22; i++){
        lE = this->findChild<QLineEdit*>("ccd_defect_" + QString::number(i + 1));
        lE->setText(QString::number(*nDefect));
        nDefect++;
    }

    for (int i = 0; i < 19; i++){
        lE = this->findChild<QLineEdit*>("ccd_trapezoid_" + QString::number(i + 1));
        lE->setText(QString::number(*fTrapezoid));
        fTrapezoid++;
    }

    for (int i = 0; i < 19; i++){
        lE = this->findChild<QLineEdit*>("ccd_rect_" + QString::number(i + 1));
        lE->setText(QString::number(*fRect));
        fRect++;
    }


    if (m_ccd.nCCD)
    {
        if (m_ccd.nAlgA)
        {
            if(m_ccd.nDefect){
                ui->tab_Alg->insertTab(0,m_tabA,QString::fromLocal8Bit("缺陷参数"));
            }
        }
        if (m_ccd.nAlgB)
        {
            switch (m_ccd.nRect)
            {
            case 1:
                // 添加尺寸1参数界面
                ui->tab_Alg->insertTab(1,m_tabB,QString::fromLocal8Bit("长(正)方形参数"));
                break;
            case 2:
                // 添加尺寸2参数界面
                ui->tab_Alg->insertTab(2,m_tabC,QString::fromLocal8Bit("梯形参数"));
                break;
            }
        }

    }
}

void MainWindow::setAlgOptions(AlgThread* tAlg,SW_AlgPart ccd)
{
    if(ccd.nCCD){
        if(ccd.nAlgA){
            tAlg->m_worker->m_nAlgDefect = ccd.nDefect;
        }else{
            tAlg->m_worker->m_nAlgDefect = 0;
        }

        if(ccd.nAlgB){
            tAlg->m_worker->m_nAlgRect = ccd.nRect;
        }else{
            tAlg->m_worker->m_nAlgRect = 0;
        }

    }else{
        tAlg->m_worker->m_nAlgDefect = 0;
        tAlg->m_worker->m_nAlgRect = 0;
    }
}
